// 导入axios
import axios from 'axios'
import store from '@/store/index'
import { Message } from 'element-ui'
import router from '@/router/index'
import { getTimeStamp } from './auth'
const tokenLongTime = 1000 * 10 * 3600
const checkTimeOut = () => {
  const loginTime = getTimeStamp()
  const nowTime = Date.now()
  return nowTime - loginTime > tokenLongTime
}
// 创建axios实例
const service = axios.create({
  //   baseURL: '/api', // 基准地址是写死的，生产环境需要手动更换
  baseURL: '/mock'
})
// 请求拦截器
service.interceptors.request.use(
  async (config) => {
    const token = store.getters.token
    if (token) {
      // 主动过期
      if (checkTimeOut()) {
        Message.error('token过期，重新登录')
        await store.dispatch('user/quitAction')
        router.push('/login')
        return Promise.reject('token过期')
      }
      config.headers['Authorization'] = 'Bearer ' + token
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)
// 响应拦截器
service.interceptors.response.use(
  (response) => {
    // console.log('走拦截器')
    const { data, message, success } = response.data
    if (success) {
      return data
    } else {
      // 业务逻辑错误
      Message.error(message)
    }
  },
  async (error) => {
    if (
      error.response &&
      error.response.data &&
      error.response.data.code === 10002
    ) {
      Message.error('token过期，重新登录')
      await store.dispatch('user/quitAction')
      router.push('/login')
    }
    return Promise.reject(error)
  }
)
// 导出axios实例
export default service
